package cn.hxzy.course.service.impl;

import cn.hxzy.common.domain.Chapter;
import cn.hxzy.common.domain.Section;
import cn.hxzy.course.mapper.ChapterMapper;
import cn.hxzy.course.mapper.SectionMapper;
import cn.hxzy.course.service.ChapterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author niuyi
 * @since 2024-06-22
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {


    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private SectionMapper sectionMapper;

    /**
     * 根据课程ID查询该课程下的所有章节
     *
     * @param courseId
     * @return
     */
    @Override
    public List<Chapter> courseList(Integer courseId) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        List<Chapter> chapters = chapterMapper.selectList(queryWrapper);
        List<Chapter> chapterList=new ArrayList<>();
        for (Chapter chapter : chapters) {
            QueryWrapper<Section> chapterQueryWrapper = new QueryWrapper<>();
            chapterQueryWrapper.eq("chapter_id", chapter.getChapterId());
            Integer i = sectionMapper.selectCount(chapterQueryWrapper);
            if(i>0){
                chapterList.add(chapter);
            }
        }
        return chapterList;
    }

    /**
     * 创建章节(某个课程下面的章节)
     *
     * @param chapter
     * @return
     */


    @Override
    public int increaseChapter(Chapter chapter) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper();
        queryWrapper.eq("chapter_name", chapter.getChapterName());
        queryWrapper.eq("course_id", chapter.getCourseId());
        List<Chapter> chapters = chapterMapper.selectList(queryWrapper);
        if (chapters.size()==0) {
            int insert = chapterMapper.insert(chapter);
            return 1;
        }
        if (chapters != null) {
            return 2;
        }
        return 0;
    }

    /**
     * 根据章节ID修改某章节
     *
     * @param chapterId
     * @return
     */

    @Override
    public int updateChapter(Integer chapterId, String chapterName) {
        int i = chapterMapper.updateChapter(chapterId, chapterName);
        return i;
    }


}
